import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

void main() => runApp(GetStateObjectRoute());

class GetStateObjectRoute extends StatefulWidget {
  @override
  State createState() => _GetStateObjectRouteState();
}


class _GetStateObjectRouteState extends State<GetStateObjectRoute> {
  static final GlobalKey<ScaffoldState> _globalKey = GlobalKey();
  @override
  Widget build(BuildContext context) {

    return MaterialApp(
      home: Scaffold(
        key: _globalKey,
        appBar: AppBar(
          title: const Text('子树中获取State对象'),
        ),
        body: Center(
          child: Column(
            children: [
              Builder(builder: (context) {
                return ElevatedButton(
                  onPressed: () {
                    ScaffoldState? _state = context.findAncestorStateOfType<ScaffoldState>();
                    _state?.openDrawer();
                  },
                  child: const Text('打开抽屉菜单1'),
                );
              }),
               Builder(builder: (context) {
                return ElevatedButton(
                  onPressed: () {
                    ScaffoldState _state = Scaffold.of(context);
                    _state.openDrawer();
                    print(_state.isDrawerOpen);
                  },
                  child: const Text('打开抽屉菜单2'),
                );
              }),
              Builder(builder: (context) {
                return ElevatedButton(
                  onPressed: () {
                    _globalKey.currentState?.openDrawer();
                  },
                  child: const Text('打开抽屉菜单3'),
                );
              }),
              Builder(builder: (context) {
                return ElevatedButton(
                  onPressed: () {
                    ScaffoldMessenger.of(context).showSnackBar(
                        const SnackBar(content: Text('我是SnackBar'))
                    );
                  },
                  child: const Text('显示SnackBar'),
                );
              }),
            ],
          ),
        ),
      ),
    );
  }
}
